<template>
  <div>
    <div>
      <van-field
        label="事故名称"
        v-model="form.AccidentName"
        name="AccidentName"
        type="textarea"
        rows="1"
        autosize
        readonly
      >
      </van-field>

      <van-field
        label="对象"
        v-model="form.AccidentObject"
        v-show="form.SystemAccidentObject == 'A' || form.SystemAccidentObject == null"
        name="AccidentObject"
        type="textarea"
        rows="1"
        autosize
        required
        @input="onChangeAccidentObject"
      ></van-field>
      <van-field
        label="后果"
        v-model="form.Consequence"
        name="Consequence"
        type="textarea"
        rows="1"
        autosize
        @input="onConsequence"
        required
      ></van-field>
      <!-- <van-field name="AccidentDepartmentName" v-model="form.AccidentDepartmentName" label="事故发生部门" placeholder="请选择" @click="goDeptment" required>
                <template #button>
                    <van-icon name="cross" @click="clearOrgCode" />
                </template>
            </van-field> -->
      <van-field
        readonly
        class="input_text"
        name="AccidentDepartmentName"
        v-model="form.AccidentDepartmentName"
        label="事故发生部门"
        placeholder="请选择"
        @click-input="goDeptment"
        required
      >
        <template #button>
          <van-icon
            name="cross"
            @click="clearOrgCode"
          />
        </template>
      </van-field>
      <!-- <div>
                <van-cell title="事故发生日期" is-link :value-class="className" :value="form.AccidentDate" @click="showPopup" />
                <van-popup v-model="timeShow" position="bottom">
                    <van-datetime-picker v-model="currentDate" type="datetime" :loading="isLoadingShow" :min-date="minDate" :max-date="maxDate" :formatter="formatter" @cancel="show = false" @confirm="confirmPicker" />
                </van-popup>
            </div> -->
      <eagle-date-picker
        label="事故发生日期"
        v-model="form.AccidentDate"
        style="align-items: center"
        required
        @cancel="show = false"
        @confirm="confirmPicker"
      ></eagle-date-picker>

      <!-- <van-field name="AccidentDate" v-model="form.AccidentDate" label="事故发生日期" placeholder="请选择事故发生时间" @click-input="showPopup" required>
                <template #button>
                    <van-popup v-model="timeShow" position="bottom">
                        <van-datetime-picker v-model="currentDate" type="datetime" :loading="isLoadingShow" :min-date="minDate" :max-date="maxDate" :formatter="formatter" @cancel="show = false" @confirm="confirmPicker" />
                    </van-popup>
                </template>
            </van-field> -->
      <van-field
        label="事故简介"
        v-model="form.Remarks"
        type="textarea"
        error-message="1.简洁；
                2.仅限于已知的事实（日期、时间、地点、发生的情况、所采取的立即行动的描述），不加任何修饰和臆断；3.事故概述中应避免出现当事人的姓名。"
        rows="2"
        autosize
        required
      />
      <van-field
        label="立即采取的行动"
        v-model="form.TakeImmediateAction"
        type="textarea"
        error-message="描述在事故后立即采取的避免事故扩大的行动（如通知、救援、撤离等）"
        rows="2"
        autosize
        required
      />
      <!-- 单选框 -->

      <van-field
        class="input_text"
        name="radio"
        label="工艺分类"
        required
      >
        <template #input>
          <van-radio-group
            v-model="form.ProcessClassification"
            direction="horizontal"
            @change="ProcessClassificationChange"
            required
          >
            <van-radio
              name="A"
              style="margin: 0 10px 10px 0"
            >工艺</van-radio>
            <van-radio
              name="B"
              style="margin: 0 10px 10px 0"
            >非工艺</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        class="input_text"
        name="radio"
        label="事故分类"
        v-if="form.ProcessClassification=='A'"
        required
      >
        <template #input>
          <van-radio-group
            v-model="form.AttidentClassification"
            direction="horizontal"
            @change="AttidentClassifyChange"
          >
            <!-- <van-radio :name="item.ID" shape="square" v-for="(item, index) in form.AccidentProcessList" :key="index">{{ item.Name }}</van-radio> -->
            <van-radio
              v-for="(item, index) in form.AccidentProcessList"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
            >{{ item.Name }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        class="input_text"
        name="radio"
        label="事故分类"
        v-if="form.ProcessClassification=='B'"
        required
      >
        <template #input>
          <van-radio-group
            v-model="form.AttidentClassification"
            direction="horizontal"
            @change="AttidentClassifyChange"
          >
            <!-- <van-radio :name="item.ID" shape="square" v-for="(item, index) in form.AccidentProcessList" :key="index">{{ item.Name }}</van-radio> -->
            <van-radio
              v-for="(item, index) in form.AccidentFreeProcessList"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
            >{{ item.Name }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- <van-field v-if="isShow(1)" name="checkboxGroup" label="伤害/职业病" required>
                <template #input v-if="isShow(1)">
                    <van-checkbox-group v-model="harmArr" direction="horizontal" @change="harmChange">
                        <van-checkbox :name="item.ID" shape="square" v-for="(item, index) in form.HarmList" :key="index">{{ item.Name }}</van-checkbox>
                    </van-checkbox-group>
                </template>
            </van-field> -->
      <van-field
        v-if="isShow(1)"
        class="input_text"
        name="checkboxGroup"
        label="伤害/职业病"
        required
      >
        <template
          #input
          v-if="isShow(1)"
        >
          <van-checkbox-group
            v-model="harmArr"
            direction="horizontal"
            @change="harmChange"
          >
            <van-checkbox
              :name="item.ID"
              shape="square"
              v-for="(item, index) in form.HarmList"
              :key="index"
            >{{ item.Name }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <van-field
        v-if="isShow(2)"
        label="火灾爆炸涉及范围"
        v-model="form.InvolveScope"
        name="InvolveScope"
        type="textarea"
        rows="1"
        autosize
        required
      ></van-field>
      <van-field
        v-if="isShow(3)"
        label="环境污染范围"
        v-model="form.PolluteScope"
        name="PolluteScope"
        type="textarea"
        rows="1"
        autosize
        required
      ></van-field>
      <van-field
        v-if="isShow(4)"
        label="泄露物质"
        v-model="form.RevealMatter"
        name="RevealMatter"
        type="textarea"
        rows="1"
        autosize
        required
      ></van-field>
      <van-field
        v-if="isShow(4)"
        label="泄露量"
        v-model="form.Spillage"
        name="Spillage"
        type="textarea"
        rows="1"
        autosize
        required
      ></van-field>
      <van-field
        v-if="isShow(5)"
        label="生产异常影响范围"
        v-model="form.SphereInfluence"
        name="SphereInfluence"
        type="textarea"
        autosize
        rows="1"
        required
      ></van-field>
      <van-field
        v-if="isShow(7)"
        label="直接财产损失"
        v-model="form.DirectPropertyLoss"
        name="DirectPropertyLoss"
        type="textarea"
        rows="1"
        autosize
        required
      ></van-field>
      <van-field
        class="input_text"
        name="radio"
        label="事故分级"
        required
        v-if="form.ProcessClassification=='A' || form.ProcessClassification=='B'"
      >
        <template #input>
          <van-radio-group
            v-model="form.AttidentgRading"
            direction="horizontal"
          >

            <van-radio
              v-for="(item, index) in form.AttidentgRadingList"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
            >{{ item.Name }}</van-radio>

            <div>
              <a
                @click="Explain"
                style="color:#00c1de"
              >说明</a>
            </div>
          </van-radio-group>

        </template>
      </van-field>
      <van-field
        class="input_text"
        name="radio"
        label="潜在风险"
        required
      >
        <template #input>
          <van-radio-group
            v-model="form.PotentialRisk"
            direction="horizontal"
          >
            <van-radio
              v-for="(item, index) in form.PotentialRiskList"
              :key="index"
              :name="item.ID"
              style="margin: 0 10px 10px 0"
            >{{ item.Name }}</van-radio>
            <div>
              <a
                @click="PotentialRiskShow1"
                style="color:#00c1de"
              >说明</a>
            </div>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        label="外部协助"
        v-model="form.ExternalAssistance"
        required
        error-message="外部机构介入、新闻媒体报道、已要求的外部协助"
        type="textarea"
        rows="2"
        autosize
      />
      <FileUpload
        @CallBack="_fileUploadCb"
        :attachs="form.Attachs"
        :labelName="'附件'"
        required
      />
      <div class="bottom-btns">
        <van-button
          type="primary"
          class="submit-two"
          @click="save(true)"
        >
          保存并提交
        </van-button>
        <van-button
          class="submit-two ml-10"
          type="info"
          @click="save(false)"
        >
          保存
        </van-button>
      </div>
    </div>
    <!-- <van-popup v-model="deptmentShow" closeable round position="bottom" :style="{ height: '80%' }">
            <div class="popup-title">选择部门</div>
            <div class="popup-content">
                <DeptmentChoose @CallBack="_chooseDeptmentCb" :SelectedValue="form.AccidentDepartmentOrg" />
            </div>
        </van-popup> -->
    <deptment-choose
      :show.sync="deptmentShow"
      :selectedValue="form.AccidentDepartmentOrg"
      @callback="chooseDeptmentCb"
      :isMulti="false"
    >
    </deptment-choose>
    <van-popup
      v-model="TheRatingShow"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title">{{this.title1}}</div>
      <div class="popup-content">
        <!-- <DeptmentChoose @CallBack="_chooseDeptmentCb" :SelectedValue="form.AccidentDepartmentOrg" /> -->
        <ExplainList
          :Type="form.ProcessClassification"
          ref="ExplainList"
        ></ExplainList>
      </div>
    </van-popup>
    <van-popup
      v-model="PotentialRiskShow"
      closeable
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="popup-title">{{this.title1}}</div>
      <div class="popup-content">
        <OverStatusDescription :Type="'PotentialRisk'"></OverStatusDescription>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  WhAccidentInitialReportSave,
  InitNewEntity,
  getDangerDetail,
} from "@/api/WhAccidentInitialReport";
import { mapGetters } from "vuex";
import store from "@/store/index";
import FileUpload from "@/components/Attach/FileUpload";
import ExplainList from "@/views/wh/AccidentInitReport/ExplainList";
import OverStatusDescription from "@/views/wh/AccidentInitReport/OverStatusDescription";
import VanFieldSelectPicker from "@/components/VanFieldSelectPicker.vue";
//import DeptmentChoose from "@/components/Department/DeptmentChoose.vue";
import DateTimePicker from "../../../components/DateTimePicker.vue";
import DeptmentChoose from "@/views/components/department/departmentChooseDialog.vue";
export default {
  components: {
    VanFieldSelectPicker,
    DeptmentChoose,
    DateTimePicker,
    FileUpload,
    ExplainList,
    OverStatusDescription,
  },
  data() {
    return {
      form: {},
      AttidentClassificationArr: [], //checkboxgroup 必须是数组类型
      harmArr: [],
      minDate: new Date(2015, 0, 1),
      showAccidentAreaDialog: false,
      edit: false,
      deptmentShow: false,
      isLoadingShow: false,
      className: "",
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      timeShow: false,
      title1: "",
      selectedValue: "",
      TheRatingShow: false,
      PotentialRiskShow: false,
    };
  },
  computed: {
    ...mapGetters(["baseUrl", "CompanyCode", "roles"]),
  },
  // watch() {},
  created() {
    let id = this.$route.query.id;
    if (id > 0) {
      this.getDangerDetail(id);
    } else {
      this.InitNewEntity();
    }
    this.calcTitle();
  },
  methods: {
    getDetail() {},
    submit() {
      var aa = this.form.PotentialRisk;
    },
    setCurrentID(itemNo, fileType) {
      this.currentItemNo = itemNo;
      this.fileType = fileType;
      this.fileOperate();
    },
    _fileUploadCb(attachs) {
      this.form.Attachs = attachs;
    },
    ProcessClassificationChange(val) {
      if (this.edit == true) {
        this.edit = false;
        return false;
      } else if (val) {
        this.form.AttidentClassification = null;
        this.AttidentClassificationArr = [];
        this.harmArr = [];
        this.form.Harm = null;
        this.form.InvolveScope = null;
        this.form.PolluteScope = null;
        this.form.RevealMatter = null;
        this.form.Spillage = null;
        this.form.SphereInfluence = null;
        this.form.DirectPropertyLoss = null;
      }
    },
    AttidentClassifyChange(val) {
      if (this.edit == true) {
        this.edit = false;
        return false;
      } else if (val) {
        this.form.InvolveScope = null;
        this.form.PolluteScope = null;
        this.form.RevealMatter = null;
        this.form.Spillage = null;
        this.form.SphereInfluence = null;
        this.form.DirectPropertyLoss = null;
        this.harmArr = [];
        this.form.Harm = null;
      }
    },
    setValue(id, name) {
      this.form.AccidentArea = id;
      this.form.AccidentAreaName = name;
    },
    setProcessClassificationValue(id, name) {
      this.form.ProcessClassification = id;
      this.form.ProcessClassificationName = name;
    },
    // handleChecked() {
    //     this.form.AttidentClassification =
    //         this.AttidentClassificationArr.join();
    // },
    isShow(value) {
      if (
        this.form.AttidentClassification &&
        this.form.AttidentClassification.indexOf(value) > -1 &&
        (value != "4" || this.form.ProcessClassification == "A") &&
        (value != "5" || this.form.ProcessClassification == "A") &&
        (value != "7" || this.form.ProcessClassification == "B")
      ) {
        return true;
      }
      return false;
    },
    Explain(item) {
      if (this.form.ProcessClassification == "A") {
        this.title1 = "工艺安全事故分级标准";
      } else if (this.form.ProcessClassification == "B") {
        this.title1 = "非工艺安全事故分级标准";
      }
      this.TheRatingShow = true;
      this.$refs.ExplainList.getList({});
      //this.$emit("getList");
    },
    PotentialRiskShow1() {
      this.PotentialRiskShow = true;
      this.title1 = "潜在风险说明";
    },
    harmChange() {
      this.form.Harm = this.harmArr.join();
    },
    setAttidentgRadingValue(data1, index, data2) {
      // data1 当前这一条的obj数据
      // index 当前选择的索引
      // data2 当前这一条数据的value
      // this.form.AttidentgRading = data1.ID;
      // this.form.AttidentgRadingName = data1.Name;
    },
    onChangeAccidentObject(val) {
      if (
        this.form.SystemAccidentObject == "A" ||
        this.form.SystemAccidentObject == null
      ) {
        this.form.AccidentName = val + this.form.Consequence;
      }
    },
    onConsequence(val) {
      if (
        this.form.SystemAccidentObject == "A" ||
        this.form.SystemAccidentObject == null
      ) {
        this.form.AccidentName = this.form.AccidentObject + val;
      } else {
        this.form.AccidentName = val;
      }
      // this.form.AccidentName =
      //     this.form.AccidentPlace + this.form.AccidentObject + val;
    },
    InitNewEntity() {
      // var me = this;
      // const param = {
      //     id: 0,
      //     ctCode: this.ctCode || "",
      //     OriginType: this.data.OriginType,
      // };
      var param = null;
      InitNewEntity(param).then((res) => {
        this.form = res.data;
        this.confirmPicker(new Date());
      });
    },
    getDangerDetail(id1) {
      const param = {
        id: id1,
      };
      var _this = this;
      getDangerDetail(param).then((res) => {
        _this.form = res.data;
        if (res.data.Harm != null) {
          _this.harmArr = res.data.Harm.split(",");
        }
        this.confirmPicker(new Date(res.data.AccidentDate));
        _this.edit = true;
      });
    },
    // 显示弹窗
    showPopup() {
      this.timeShow = true;
      this.isLoadingShow = true;
      setTimeout(() => {
        this.isLoadingShow = false;
      }, 500);
    },
    // 确认选择的时间
    confirmPicker(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      this.className = "timeClass";
      this.timeValue = `${year}-${month}-${day} ${hour}:${minute}`;
      this.timeShow = false;
      this.form.AccidentDate = this.timeValue;
    },
    // 选项格式化函数
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      } else if (type === "second") {
        return `${value}秒`;
      }
      return value;
    },
    save(IsPublish) {
      if (
        !this.form.AccidentObject &&
        (this.form.SystemAccidentObject == "A" ||
          this.form.SystemAccidentObject == null)
      ) {
        this.$toast("请输入对象");
        return;
      }
      if (!this.form.AccidentDate) {
        this.$toast("请选择事故发生日期");
        return;
      }

      if (!this.form.ProcessClassification) {
        this.$toast("请选择工艺分类");
        return;
      }
      if (!this.form.AttidentgRading) {
        this.$toast("请选择事故分级");
        return;
      }
      if (!this.form.PotentialRisk) {
        this.$toast("请选择潜在风险");
        return;
      }
      if (!this.form.Consequence) {
        this.$toast("请输入后果");
        return;
      }
      if (!this.form.Remarks) {
        this.$toast("请输入简介");
        return;
      }
      if (!this.form.AttidentClassification) {
        this.$toast("请选择事故分类");
        return;
      }
      if (!this.form.ExternalAssistance) {
        this.$toast("请输入外部协助");
        return;
      }
      if (!this.form.TakeImmediateAction) {
        this.$toast("请输入立即采取的行动");
        return;
      }
      if (!this.form.AccidentDepartmentName) {
        this.$toast("请选择事故发生部门");
        return;
      }

      if (
        !this.form.Harm &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "1"
      ) {
        this.$toast("请选择伤害/职业病");
        return;
      }
      if (
        !this.form.InvolveScope &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "2"
      ) {
        this.$toast("请输入火灾爆炸涉及范围");
        return;
      }
      if (
        !this.form.PolluteScope &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "3"
      ) {
        this.$toast("请输入环境污染范围");
        return;
      }
      if (
        !this.form.RevealMatter &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "4"
      ) {
        this.$toast("请输入泄露物质");
        return;
      }
      if (
        !this.form.Spillage &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "4"
      ) {
        this.$toast("请输入泄露量");
        return;
      }
      if (
        !this.form.SphereInfluence &&
        this.form.ProcessClassification == "A" &&
        this.form.AttidentClassification == "5"
      ) {
        this.$toast("请输入生产异常影响范围");
        return;
      }
      if (
        !this.form.InvolveScope &&
        this.form.ProcessClassification == "B" &&
        this.form.AttidentClassification == "2"
      ) {
        this.$toast("请输入火灾爆炸涉及范围");
        return;
      }
      if (
        !this.form.PolluteScope &&
        this.form.ProcessClassification == "B" &&
        this.form.AttidentClassification == "3"
      ) {
        this.$toast("请输入环境污染范围");
        return;
      }
      if (
        !this.form.DirectPropertyLoss &&
        this.form.ProcessClassification == "B" &&
        this.form.AttidentClassification == "7"
      ) {
        this.$toast("请输入直接财产损失");
        return;
      }
      this.loading = true;
      let param = {};
      let form1 = this.form;
      form1.IsPublish = IsPublish;
      // this.form.forEach((item) => {
      //     param[item.FieldName] = item.Value;
      //     if (item.ShowRelatedFieldKey) {
      //         param[item.RelatedFieldName] = item.RelatedFieldValue;
      //     }
      // });
      WhAccidentInitialReportSave(form1)
        .then((res) => {
          this.loading = false;
          this.$toast.success("保存成功！");
          setTimeout(() => {
            this.$router.goRefresh(-1);
          }, 300);
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    // 部门
    goDeptment() {
      this.deptmentShow = true;
    },
    chooseDeptmentCb(item) {
      // this.$set(this.form, "AccidentDepartmentName", item.name || "");
      // this.$set(this.form, "AccidentDepartmentOrg", item.value || "");
      this.form.AccidentDepartmentName = item.name;
      this.form.AccidentDepartmentOrg = item.code;
      this.deptmentShow = false;
    },
    clearOrgCode() {
      this.form.AccidentDepartmentOrg = "";
      this.form.AccidentDepartmentName = "";
    },
    calcTitle() {
      let id = this.$route.query.id;
      let title = "";
      if (id > 0) {
        title = "初始报告[编辑]";
      } else {
        title = "初始报告[新增]";
      }
      store.commit("updateTitle", title);
    },
  },
};
</script>

<style lang="less" scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.block {
  width: 120px;
  height: 120px;
  background-color: #fff;
}
/deep/.van-field__error-message {
  color: unset;
}
.bottom-btns {
  margin-top: 10px;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .submit-btn {
    width: 30%;
    height: 30px;
    font-size: 12px;
  }
  .submit-only {
    width: 100%;
    height: 30px;
    font-size: 12px;
  }
  .submit-two {
    width: 48%;
    height: 30px;
    font-size: 12px;
  }
}

.space-between {
  justify-content: space-between;
}
</style>
